package org.mbcorp.sar.util.mail;

import java.util.Date;

import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.mbcorp.sar.model.Alerta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 * 
 * Created with IntelliJ IDEA. 
 * User: sverma 
 * Date: 4/12/12 
 * Time: 5:18 PM
 */

public class AMQAlertaEmailListener implements MessageListener {

	@Autowired
	MailSender mailSender;

	public void onMessage(Message message) {

		System.out.println("OnMessage: Email Listener working... " + message);
		System.out.println("OnMessage: Email message instance matched = " + (message instanceof ActiveMQObjectMessage));

		if (message instanceof ActiveMQObjectMessage)
		{
			try
			{
				System.out.println("Converting object to Alerta class for email.");
				Alerta alerta = (Alerta) ((ActiveMQObjectMessage) message).getObject();

				System.out.println("OnMessage: Email Object received in Listener as " + alerta);

				/* call message sender to put message onto second queue */

				System.out.println("Sending mail for alerta " + alerta);
				SimpleMailMessage msg = new SimpleMailMessage();
				msg.setTo(alerta.getEmailDestino());
				msg.setFrom("sarmbcorp@gmail.com");
				msg.setSubject(alerta.getAsunto());
				msg.setSentDate(new Date());
				msg.setText(alerta.getCuerpo());
				System.out.println("Espera intencional de 10 segundos antes de mandar correo...");

				Thread.sleep(10000); // Mail server was throwing error of
										// message sending limit in given time
										// frame exceeds

				mailSender.send(msg);
			}

			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}